<template>
  <view class="newPost">
    <view class="con">
      <view class="title"> 输入正文 </view>
      <van-field
        style="width: 95%"
        v-model:value="postContext"
        size="large"
        rows="1"
        maxlength="200"
        show-word-limit
        :autosize="{ maxHeight: 80, minHeight: 50 }"
        type="textarea"
        placeholder="请输入内容"
        @input="changeValue"
      />
    </view>
    <view class="con">
      <view class="title"> 选择类型 </view>
      <van-radio-group v-model="postType">
        <van-cell-group>
          <van-cell size="large" clickable @click="postType = '0'">
            <template>
              <van-radio icon-size="60rpx" name="0">
                <span style="font-size: 40rpx">公告</span>
              </van-radio>
            </template>
          </van-cell>
          <van-cell size="large" clickable @click="postType = '1'">
            <template>
              <van-radio icon-size="60rpx" name="1">
                <span style="font-size: 40rpx">失物招领</span>
              </van-radio>
            </template>
          </van-cell>
          <van-cell size="large" clickable @click="postType = '2'">
            <template>
              <van-radio icon-size="60rpx" name="2">
                <span style="font-size: 40rpx">意见反馈</span>
              </van-radio>
            </template>
          </van-cell>
        </van-cell-group>
      </van-radio-group>
    </view>
    <view class="con">
      <view class="title"> 上传图片 </view>
      <view class="imgList">
        <view v-for="(url, index) in fileList" class="uploadImgs">
          <image
            style="height: 200rpx; width: 200rpx"
            :src="url"
            mode="aspectFill"
            @click="previewImage(url, index)"
          ></image>
          <view class="deleteIcon" @click.stop="removeImage(index)">
            <van-icon name="close" />
          </view>
        </view>
        <view
          v-if="fileList.length < 9"
          @click="chooseImg"
          style="border: 2rpx dashed rgba(0, 0, 0, 0.5)"
          class="uploadImgs"
        >
          <van-icon size="100rpx" name="add-o" />
        </view>
      </view>
    </view>
    <view class="con">
      <van-button @click="submitPost" block type="primary" size="large"
        >提交审核</van-button
      >
    </view>
  </view>
</template>

<script setup>
import { ref } from "vue";
// import { useCloudStore } from "@/store";
const fileList = ref([]);
// const { isInitCloud } = useCloudStore();
const removeImage = (index) => {
  fileList.value.splice(index, 1);
};
import { newPost } from "@/apis/apis.js";
const postType = ref(1);

const postContext = ref("");
const changeValue = (e) => {
  postContext.value = e.detail;
};
const chooseImg = () => {
  const p = new Promise((resolve, reject) => {
    uni.chooseImage({
      count: 9, // 默认9
      sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
      sourceType: ["album"], // 从相册选择
      success: function (res) {
        const newImages = res.tempFilePaths.filter(
          (path) => !fileList.value.includes(path)
        );
        fileList.value = [...fileList.value, ...newImages];
        Promise.all(newImages.map((filePath) => uploadImgs(filePath)))
          .then((results) => {
            resolve(results);
          })
          .catch((err) => {
            reject(err);
          });
      },
      fail: function (err) {
        reject("图片选择失败", err);
      },
    });
  });
  p.then((result) => {
    console.log("上传图片的jieguo", result);
  });
};

const uploadImgs = (filePath) => {
  return new Promise((resolve, reject) => {
    const cloudPath = `postImg/${new Date().getTime()}.png`;
    wx.cloud
      .uploadFile({
        cloudPath,
        filePath,
        config: {
          env: "prod-5gduafzd5d123d73",
        },
      })
      .then((res) => {
        resolve({ res, sessionPath: filePath, cloudPath, state: "success" });
      })
      .catch((err) => {
        reject({ res: err, state: "fail" });
      });
  });
};

const previewImage = (url, index) => {
  console.log("photoImg", url);
  let imgsArray = fileList.value;
  uni.previewImage({
    current: index,
    urls: imgsArray,
  });
};

const submitPost = () => {
  if (!postContext.value.trim()) {
    uni.showToast({
      title: "请输入正文内容",
      icon: "none",
    });
    return;
  }
  if (!postType.value) {
    uni.showToast({
      title: "请选择帖子类型",
      icon: "none",
    });
    return;
  }
  if (fileList.value.length === 0) {
    uni.showToast({
      title: "请上传图片",
      icon: "none",
    });
    return;
  }

  const postData = {
    content: postContext.value,
    type: postType.value,
    imgUrls: fileList.value,
  };

  newPost(postData)
    .then(() => {
      uni.showToast({
        title: "提交成功",
      });
    })
    .catch((error) => {
      console.error(error);
      uni.showToast({
        title: "提交失败",
        icon: "none",
      });
    });
};
</script>

<style lang="less" scoped>
.newPost {
  width: 100vw;
  padding-top: 50rpx;
  background-color: white;

  .con {
    width: 100%;
    height: auto;
    min-height: 300rpx;
    padding: 20rpx;
    box-sizing: border-box;
    display: flex;
    flex-direction: column;

    .title {
      font-size: 38rpx;
      padding-bottom: 40rpx;
    }

    .imgList {
      min-width: 80%;
      margin-top: 20rpx;
      padding: 10rpx;
      display: flex;
      flex-wrap: wrap;
      gap: 20rpx;

      .uploadImgs {
        width: 200rpx;
        height: 200rpx;
        display: inline-block;
        vertical-align: top;
        overflow: hidden;
        background-color: #f7f8fa;
        border-radius: 15rpx;
        display: flex;
        justify-content: center;
        align-items: center;
        box-sizing: border-box;
        position: relative;
        border: 2rpx solid rgba(0, 0, 0, 0.3);

        image {
          width: 100%;
          height: 100%;
          border-radius: 15rpx;
        }

        .deleteIcon {
          position: absolute;
          top: 10rpx;
          right: 10rpx;
          width: 50rpx;
          height: 50rpx;
          background-color: rgba(0, 0, 0, 0.5);
          border-radius: 50%;
          display: flex;
          justify-content: center;
          align-items: center;
          color: white;
        }
      }
    }
  }
}
</style>
